<?php
class Album extends ARAlbum {
	public $authorQuestion;
	public $authorAnswer;
	public $isPrivate; //启用anonymous 验证;
	public $anonymousQuestion;
	public $anonymousAnswer;
	
	public function rules() {
		static $rules;
		
		return empty ( $rules ) ? $rules = array (
			array('authorQuestion, authorAnswer', 'required', 'on' => 'insert'),
			array('authorQuestionId', 'insertAuthorQuestion', 'on' => 'insert, update'),
			array('anonymousQuestionId', 'insertAnonymousQuestion', 'on' => 'insert, update'),
			array('title', 'required'),
			array('title', 'length', 'min' => '2', 'max' => '1000'),
		) : $rules;
	}

	public function attributeLabels() {
		static $labels;
		return empty ( $labels ) ? $labels = array (
			'title' => '专辑',
			'title_info' => '填写专辑名',
			'content' => '描述',
			'content_info' => '相册的简介',
			'authorQuestion' => '问题(作者)',
			'authorQuestion_info' => '填写作者验证口令.验证后可以修改相册信息',
			'authorAnswer' => '回答',
			'isPrivate' => '设置访客验证问题',
			'isPrivate_info' => '如果勾选,其他人访问该相册时需要验证问题',
			'anonymousQuestion' => '问题(访客)',
			'anonymousQuestion_info' => '填写访客验证口令.不填写则视为公开相册',
			'anonymousAnswer' => '回答' 
		) : $labels;
	}

	public function relations() {
		return array (
			'photo' => array( self::HAS_MANY, 'AlbumPhoto', 'aid' ),
			'questionAuthor' => array(self::BELONGS_TO, 'AlbumQuestion', 'authorQuestionId'),
			'questionAnonymous' => array(self::HAS_ONE, 'AlbumQuestion', 'qid')
		);
	}
	
	public function insertAuthorQuestion($attribute, $params){
		$albumQuestion = new AlbumQuestion();
		if ($id = $albumQuestion->insertQuestion ( $this->authorQuestion, $this->authorAnswer ))
			$this->authorQuestionId = $id;
		else
			foreach($albumQuestion->getErrors() as $key => $errorMessage){
				$key = 'author' . ucwords ( $key );
				$this->addError ( $key, $errorMessage );
			}
	}
	
	public function insertAnonymousQuestion($attribute, $params){
		if($this->isPrivate){
			$albumQuestion = new AlbumQuestion();
			if ($id = $albumQuestion->insertQuestion ( $this->anonymousQuestion, $this->anonymousAnswer ))
				$this->anonymousQuestionId = $id;
			else
				foreach($albumQuestion->getErrors() as $key => $errorMessage){
					$key = 'anonymous' . ucwords ( $key );
					$this->addError ( $key, $errorMessage );
				}
		}
	}
	
	/**
	 * 增加评论
	 * @param AlbumComment $comment
	 */
	public function addComment(AlbumComment $comment){
		$comment->aid = $this->aid;
		if($return = $comment->save())
			$this->updateReplies();
		return $return;
	}
	
	
	/**
	 * 更新相册评论数
	 * @param int $num
	 */
	public function updateReplies($num = 1){
		return $this->updateByPk($this->aid, array('replies' => $this->replies + (int)$num));
	}
}